/*
 * @Description: 定位
 * @Author: Kerwin
 * @Date: 2025-05-19 15:29:49
 * @LastEditTime: 2025-11-20 11:26:13
 * @LastEditors:  Please set LastEditors
 */

import { watch, ref, reactive } from 'vue'
//#region ************ api ********************** */
import { baseApi, moneyApi, userApi, productApi } from '@/api'
//工具
import { getWZLocation } from '@/utils'
import { useUserStore } from '@/store'

const WZAdress = ref()
const userStore = useUserStore()
// 获取用户定位（来自用户信息）
export const userLocation = async () => {
  const { data } = await userApi.userInfo()
  userStore.syncSetUserInfo(data)
  return { latitude: data.latitude, longitude: data.longitude }
}

// 定位逆解析
const getAddress = async (address: any) => {
  uni.setStorageSync('wzLocation', address)
  const { data } = await baseApi.reverseGeocodingWZ(address)
  if (data) {
    WZAdress.value = data
    uni.setStorageSync('wzLocation', data)
  }
}

// 封装定位获取逻辑，支持 fallback
const getLocationWithFallback = async () => {
  try {
    return await getWZLocation()
  } catch (err) {
    console.warn('getWZLocation 失败，尝试兜底方案')
    return {
      latitude: 30.672477,
      longitude: 104.066534
    } // 默认成都坐标兜底
  }
}

/**
 * 获取定位并进行逆解析
 */
export const getLocationInfo = async () => {
  let source = ''
  let location = uni.getStorageSync('userLocation')

  if (
    location &&
    typeof location.latitude === 'number' &&
    typeof location.longitude === 'number'
  ) {
    source = 'app函数传递的定位--缓存'
    console.log('使用缓存定位:', location)
  } else {
    try {
      location = await userLocation()
      if (
        location &&
        typeof location.latitude === 'number' &&
        typeof location.longitude === 'number'
      ) {
        source = '用户信息接口'
      } else {
        location = await getLocationWithFallback()
        source = '兜底定位'
      }
    } catch (e) {
      location = await getLocationWithFallback()
      source = '兜底定位'
    }

    uni.setStorageSync('userLocation', location)
  }

  console.log(`🎯 使用${source}作为定位`)
  await getAddress(location)

  return {
    location,
    address: WZAdress.value
  }
}
